package jsonparser;

import java.util.LinkedList;

/**
 * Created by pendragon on 17-5-20.
 */
public class JSONArray {
    private StringBuilder sb;

    private LinkedList<Object> array;

    public JSONArray(){
        array = new LinkedList<>();
    }

    public void addValue(Object object){
        array.add(object);
    }

    public Object get(int index) {
        return array.get(index);
    }

    @Override
    public String toString() {
        format();
        return sb.toString();
    }

    protected void format(StringBuilder sb, int n){
        fillTab(sb, n);

        for (Object o : array){
            sb.append('\n');
            fillTab(sb, n + 1);

            if (o instanceof String){
                sb.append('"')
                        .append(o)
                        .append('"');
            } else if (o instanceof JSONObject){
                sb.append('{');
                ((JSONObject)o).format(sb, n + 1);
            } else if (o instanceof JSONArray){
                sb.append('[');
                ((JSONArray)o).format(sb, n + 1);
            } else {
                sb.append(o);
            }

            sb.append(',');
        }

        sb.deleteCharAt(sb.length() - 1);
        sb.append('\n');
        fillTab(sb, n);
        sb.append(']');
    }

    private void format(){
        sb = new StringBuilder();
        sb.append('[');
        format(sb, 0);
    }

    private void fillTab(StringBuilder sb, int n){
        for (int i = 0; i < n; i++){
            sb.append('\t');
        }
    }
}
